#!/usr/bin/env python3
"""
简化版GUI+Web预览监控器
使用tkinter + webview实现，减少依赖
"""

import os
import sys
import json
import base64
import threading
import time
import hashlib
import webbrowser
from io import BytesIO
import numpy as np
from PIL import Image
import tkinter as tk
from tkinter import ttk, messagebox
import subprocess
import tempfile

# 尝试导入webview
try:
    import webview
    WEBVIEW_AVAILABLE = True
except ImportError:
    WEBVIEW_AVAILABLE = False
    print("[ERROR] webview not available. Install with: pip install pywebview")

class SimpleGUIPreviewMonitor:
    """简化版GUI预览监控器"""
    
    def __init__(self):
        self.root = tk.Tk()
        self.root.title("Simple GUI Preview Monitor")
        self.root.geometry("800x600")
        
        self.image_cache = {}
        self.current_images = []
        self.current_index = 0
        self.zoom = 1.0
        self.pan_x = 0
        self.pan_y = 0
        
        self.setup_ui()
        self.setup_webview()
    
    def setup_ui(self):
        """设置UI界面"""
        # 创建主框架
        main_frame = ttk.Frame(self.root)
        main_frame.pack(fill=tk.BOTH, expand=True)
        
        # 控制面板
        control_frame = ttk.LabelFrame(main_frame, text="Controls")
        control_frame.pack(side=tk.LEFT, fill=tk.Y, padx=5, pady=5)
        
        # 连接按钮
        self.connect_btn = ttk.Button(control_frame, text="Connect to ComfyUI", command=self.connect_to_comfyui)
        self.connect_btn.pack(pady=5)
        
        # 图片信息
        self.info_label = ttk.Label(control_frame, text="No images")
        self.info_label.pack(pady=5)
        
        # 控制按钮
        button_frame = ttk.Frame(control_frame)
        button_frame.pack(pady=5)
        
        self.prev_btn = ttk.Button(button_frame, text="Previous", command=self.previous_image)
        self.prev_btn.pack(side=tk.LEFT, padx=2)
        
        self.next_btn = ttk.Button(button_frame, text="Next", command=self.next_image)
        self.next_btn.pack(side=tk.LEFT, padx=2)
        
        self.reset_btn = ttk.Button(button_frame, text="Reset", command=self.reset_view)
        self.reset_btn.pack(side=tk.LEFT, padx=2)
        
        # 缩放控制
        zoom_frame = ttk.Frame(control_frame)
        zoom_frame.pack(pady=5)
        
        ttk.Label(zoom_frame, text="Zoom:").pack(side=tk.LEFT)
        self.zoom_var = tk.DoubleVar(value=1.0)
        self.zoom_scale = ttk.Scale(zoom_frame, from_=0.1, to=5.0, variable=self.zoom_var, 
                                  orient=tk.HORIZONTAL, command=self.on_zoom_changed)
        self.zoom_scale.pack(side=tk.LEFT, padx=5)
        
        self.zoom_label = ttk.Label(zoom_frame, text="100%")
        self.zoom_label.pack(side=tk.LEFT)
        
        # 显示模式
        mode_frame = ttk.Frame(control_frame)
        mode_frame.pack(pady=5)
        
        ttk.Label(mode_frame, text="Mode:").pack(side=tk.LEFT)
        self.mode_var = tk.StringVar(value="Single")
        self.mode_combo = ttk.Combobox(mode_frame, textvariable=self.mode_var, 
                                      values=["Single", "Comparison", "Slideshow"], state="readonly")
        self.mode_combo.pack(side=tk.LEFT, padx=5)
        self.mode_combo.bind("<<ComboboxSelected>>", self.on_mode_changed)
        
        # 日志区域
        log_frame = ttk.LabelFrame(control_frame, text="Log")
        log_frame.pack(fill=tk.BOTH, expand=True, pady=5)
        
        self.log_text = tk.Text(log_frame, height=10, width=30)
        log_scrollbar = ttk.Scrollbar(log_frame, orient=tk.VERTICAL, command=self.log_text.yview)
        self.log_text.configure(yscrollcommand=log_scrollbar.set)
        
        self.log_text.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
        log_scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        
        # 预览区域
        self.preview_frame = ttk.LabelFrame(main_frame, text="Preview")
        self.preview_frame.pack(side=tk.RIGHT, fill=tk.BOTH, expand=True, padx=5, pady=5)
        
        # 创建HTML预览区域
        self.preview_html = self.create_preview_html()
        
        # 键盘绑定
        self.root.bind("<KeyPress>", self.on_key_press)
        self.root.focus_set()
    
    def setup_webview(self):
        """设置webview"""
        if WEBVIEW_AVAILABLE:
            # 使用pywebview
            self.webview = webview.create_window(
                title="Preview Monitor",
                html=self.preview_html,
                width=600,
                height=400,
                resizable=True
            )
        else:
            # 使用tkinter的webview替代
            self.create_tkinter_preview()
    
    def create_tkinter_preview(self):
        """创建tkinter预览区域"""
        # 创建画布
        self.canvas = tk.Canvas(self.preview_frame, bg="black")
        self.canvas.pack(fill=tk.BOTH, expand=True)
        
        # 绑定鼠标事件
        self.canvas.bind("<Button-1>", self.on_canvas_click)
        self.canvas.bind("<B1-Motion>", self.on_canvas_drag)
        self.canvas.bind("<MouseWheel>", self.on_canvas_wheel)
        
        # 显示提示
        self.canvas.create_text(300, 200, text="Preview Area\n(WebView not available)", 
                               fill="white", font=("Arial", 16))
    
    def create_preview_html(self):
        """创建预览HTML"""
        return '''<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Simple Preview Monitor</title>
    <style>
        body {
            background: #000;
            margin: 0;
            padding: 0;
            overflow: hidden;
            font-family: Arial, sans-serif;
        }
        
        #canvas {
            width: 100%;
            height: 100vh;
            cursor: crosshair;
        }
        
        #controls {
            position: absolute;
            top: 10px;
            left: 10px;
            background: rgba(0, 0, 0, 0.8);
            color: white;
            padding: 10px;
            border-radius: 5px;
            font-size: 12px;
        }
        
        #status {
            position: absolute;
            bottom: 10px;
            right: 10px;
            background: rgba(0, 0, 0, 0.8);
            color: white;
            padding: 10px;
            border-radius: 5px;
            font-size: 12px;
        }
    </style>
</head>
<body>
    <canvas id="canvas"></canvas>
    
    <div id="controls">
        <div>Simple Preview Monitor</div>
        <div>Images: <span id="image-count">0</span></div>
        <div>Zoom: <span id="zoom">100%</span></div>
    </div>
    
    <div id="status">
        <div>Mouse: <span id="mouse-pos">0, 0</span></div>
        <div>FPS: <span id="fps">0</span></div>
    </div>
    
    <script>
        class SimplePreviewMonitor {
            constructor() {
                this.canvas = document.getElementById('canvas');
                this.ctx = this.canvas.getContext('2d');
                
                this.images = [];
                this.currentImageIndex = 0;
                this.zoom = 1.0;
                this.panX = 0;
                this.panY = 0;
                this.mouseX = 0;
                this.mouseY = 0;
                this.dragging = false;
                this.lastMousePos = { x: 0, y: 0 };
                
                this.fps = 0;
                this.lastTime = 0;
                this.frameCount = 0;
                
                this.setupEventListeners();
                this.resizeCanvas();
                this.animate();
            }
            
            setupEventListeners() {
                this.canvas.addEventListener('mousemove', (e) => {
                    const rect = this.canvas.getBoundingClientRect();
                    this.mouseX = e.clientX - rect.left;
                    this.mouseY = e.clientY - rect.top;
                    
                    if (this.dragging) {
                        const dx = this.mouseX - this.lastMousePos.x;
                        const dy = this.mouseY - this.lastMousePos.y;
                        this.panX += dx;
                        this.panY += dy;
                    }
                    
                    this.lastMousePos = { x: this.mouseX, y: this.mouseY };
                });
                
                this.canvas.addEventListener('mousedown', (e) => {
                    if (e.button === 0) {
                        this.dragging = true;
                    }
                });
                
                this.canvas.addEventListener('mouseup', (e) => {
                    this.dragging = false;
                });
                
                this.canvas.addEventListener('wheel', (e) => {
                    e.preventDefault();
                    
                    const rect = this.canvas.getBoundingClientRect();
                    const mouseX = e.clientX - rect.left;
                    const mouseY = e.clientY - rect.top;
                    
                    const oldZoom = this.zoom;
                    const delta = e.deltaY > 0 ? 0.9 : 1.1;
                    this.zoom = Math.max(0.1, Math.min(10, this.zoom * delta));
                    
                    if (oldZoom !== this.zoom) {
                        const worldX = (mouseX - this.canvas.width / 2 - this.panX) / oldZoom;
                        const worldY = (mouseY - this.canvas.height / 2 - this.panY) / oldZoom;
                        
                        this.panX = mouseX - this.canvas.width / 2 - worldX * this.zoom;
                        this.panY = mouseY - this.canvas.height / 2 - worldY * this.zoom;
                    }
                    
                    this.updateDisplay();
                });
                
                document.addEventListener('keydown', (e) => {
                    switch(e.key) {
                        case 'ArrowLeft':
                            this.previousImage();
                            break;
                        case 'ArrowRight':
                            this.nextImage();
                            break;
                        case 'r':
                        case 'R':
                            this.resetView();
                            break;
                    }
                });
                
                window.addEventListener('resize', () => {
                    this.resizeCanvas();
                });
            }
            
            resizeCanvas() {
                this.canvas.width = window.innerWidth;
                this.canvas.height = window.innerHeight;
            }
            
            updateDisplay() {
                if (this.images.length === 0) return;
                
                const currentImage = this.images[this.currentImageIndex];
                if (!currentImage) return;
                
                this.drawImage(currentImage);
                this.updateUI();
            }
            
            drawImage(img) {
                const canvas = this.canvas;
                const ctx = this.ctx;
                
                ctx.fillStyle = '#000000';
                ctx.fillRect(0, 0, canvas.width, canvas.height);
                
                const imgWidth = img.width * this.zoom;
                const imgHeight = img.height * this.zoom;
                
                const x = (canvas.width - imgWidth) / 2 + this.panX;
                const y = (canvas.height - imgHeight) / 2 + this.panY;
                
                ctx.drawImage(img, x, y, imgWidth, imgHeight);
            }
            
            updateUI() {
                document.getElementById('image-count').textContent = this.images.length;
                document.getElementById('zoom').textContent = Math.round(this.zoom * 100) + '%';
                document.getElementById('mouse-pos').textContent = `${Math.round(this.mouseX)}, ${Math.round(this.mouseY)}`;
                document.getElementById('fps').textContent = this.fps;
            }
            
            nextImage() {
                if (this.images.length > 1) {
                    this.currentImageIndex = (this.currentImageIndex + 1) % this.images.length;
                    this.updateDisplay();
                }
            }
            
            previousImage() {
                if (this.images.length > 1) {
                    this.currentImageIndex = (this.currentImageIndex - 1 + this.images.length) % this.images.length;
                    this.updateDisplay();
                }
            }
            
            resetView() {
                this.zoom = 1.0;
                this.panX = 0;
                this.panY = 0;
                this.updateDisplay();
            }
            
            animate() {
                const now = performance.now();
                this.frameCount++;
                
                if (now - this.lastTime >= 1000) {
                    this.fps = Math.round((this.frameCount * 1000) / (now - this.lastTime));
                    this.frameCount = 0;
                    this.lastTime = now;
                }
                
                this.updateUI();
                requestAnimationFrame(() => this.animate());
            }
        }
        
        // 初始化
        document.addEventListener('DOMContentLoaded', () => {
            window.previewMonitor = new SimplePreviewMonitor();
        });
    </script>
</body>
</html>'''
    
    def connect_to_comfyui(self):
        """连接到ComfyUI"""
        self.log_message("Connecting to ComfyUI...")
        # 模拟连接
        self.log_message("Connected to ComfyUI")
        self.info_label.config(text="Connected")
    
    def previous_image(self):
        """上一张图片"""
        if self.current_images:
            self.current_index = (self.current_index - 1) % len(self.current_images)
            self.update_display()
            self.log_message(f"Previous image: {self.current_index + 1}/{len(self.current_images)}")
    
    def next_image(self):
        """下一张图片"""
        if self.current_images:
            self.current_index = (self.current_index + 1) % len(self.current_images)
            self.update_display()
            self.log_message(f"Next image: {self.current_index + 1}/{len(self.current_images)}")
    
    def reset_view(self):
        """重置视图"""
        self.zoom = 1.0
        self.pan_x = 0
        self.pan_y = 0
        self.zoom_var.set(1.0)
        self.update_display()
        self.log_message("View reset")
    
    def on_zoom_changed(self, value):
        """缩放改变"""
        self.zoom = float(value)
        self.zoom_label.config(text=f"{int(self.zoom * 100)}%")
        self.update_display()
    
    def on_mode_changed(self, event):
        """显示模式改变"""
        mode = self.mode_var.get()
        self.log_message(f"Display mode changed to {mode}")
    
    def on_key_press(self, event):
        """键盘事件"""
        if event.keysym == "Left":
            self.previous_image()
        elif event.keysym == "Right":
            self.next_image()
        elif event.keysym == "r":
            self.reset_view()
    
    def on_canvas_click(self, event):
        """画布点击事件"""
        self.last_mouse_x = event.x
        self.last_mouse_y = event.y
        self.log_message(f"Canvas clicked at ({event.x}, {event.y})")
    
    def on_canvas_drag(self, event):
        """画布拖拽事件"""
        if hasattr(self, 'last_mouse_x') and hasattr(self, 'last_mouse_y'):
            self.pan_x += event.x - self.last_mouse_x
            self.pan_y += event.y - self.last_mouse_y
        self.last_mouse_x = event.x
        self.last_mouse_y = event.y
        self.update_display()
    
    def on_canvas_wheel(self, event):
        """画布滚轮事件"""
        delta = 1.1 if event.delta > 0 else 0.9
        self.zoom = max(0.1, min(5.0, self.zoom * delta))
        self.zoom_var.set(self.zoom)
        self.zoom_label.config(text=f"{int(self.zoom * 100)}%")
        self.update_display()
    
    def update_display(self):
        """更新显示"""
        if self.current_images:
            self.info_label.config(text=f"Images: {len(self.current_images)} ({self.current_index + 1}/{len(self.current_images)})")
    
    def log_message(self, message):
        """记录日志消息"""
        timestamp = time.strftime("%H:%M:%S")
        log_entry = f"[{timestamp}] {message}\n"
        self.log_text.insert(tk.END, log_entry)
        self.log_text.see(tk.END)
    
    def add_images(self, images):
        """添加图片"""
        self.current_images = images
        self.current_index = 0
        self.update_display()
        self.log_message(f"Added {len(images)} images")
    
    def run(self):
        """运行应用"""
        self.root.mainloop()

def test_simple_gui():
    """测试简化版GUI"""
    print("🔍 [DEBUG] Testing Simple GUI Preview Monitor...")
    
    # 创建测试图片
    test_images = []
    colors = [(255, 0, 0), (0, 255, 0), (0, 0, 255), (255, 255, 0), (255, 0, 255)]
    
    for i, color in enumerate(colors):
        img = np.zeros((512, 512, 3), dtype=np.uint8)
        img[:, :] = color
        test_images.append(img)
        print(f"✅ [DEBUG] Created test image {i+1} with color {color}")
    
    # 创建GUI
    app = SimpleGUIPreviewMonitor()
    app.add_images(test_images)
    
    print("✅ [DEBUG] GUI window should be visible now")
    print("Controls:")
    print("- Left/Right arrows: Navigate images")
    print("- R: Reset view")
    print("- Mouse wheel: Zoom")
    print("- Mouse drag: Pan")
    
    # 运行应用
    app.run()

if __name__ == "__main__":
    test_simple_gui()
